import React, { useState, useEffect } from 'react';
import styles from './list.less';
import { Link, history } from 'umi';
import { Fragment } from 'react';
import { Button } from 'antd';
import utils from '../../utils';
const { storage } = utils;

const toNew = () => {
  history.push('/edit');
};

const getOld = (id: string): any => {
  const oldArr = storage.get('formio_demo_save') || [];
  const oldVal = oldArr.find((i) => i.id == id);
  return oldVal;
};

export default function List(props: Props) {
  const params = props.match && props.match.params ? props.match.params : {};
  const id = params.id;
  const _listData = storage.get('formio_demo_save');
  const [listData, setListData] = useState(_listData);

  const del = (id: string | number | undefined) => {
    if (!window.confirm('确认要删除吗？')) return;

    const oldArr = storage.get('formio_demo_save') || [];
    const oldValIdx = oldArr.findIndex((i) => i.id === id);
    if (oldValIdx >= 0) oldArr.splice(oldValIdx, 1);
    storage.set('formio_demo_save', oldArr);
    setListData(oldArr);
  };

  const calumns =
    listData && listData.length ? (
      listData.map((data: ListData, index: number) => (
        <tr key={data.id}>
          <th scope="row">{index + 1}</th>
          <td>{data.name}</td>
          <td>{data.id}</td>
          <td>
            <Link to={`/edit/${data.id}`}>查看</Link>
            <Button type="link" danger onClick={() => del(data.id)}>
              删除
            </Button>
          </td>
        </tr>
      ))
    ) : (
      <tr>
        <td>
          <div>暂无数据</div>
        </td>
      </tr>
    );

  return (
    <div className={styles.box}>
      <div className={styles.listTop}>
        <span className="btn btn-primary" onClick={toNew}>
          New
        </span>
      </div>
      <div className={styles.list}>
        <table className="table">
          <thead>
            <tr>
              <th scope="col">#</th>
              <th scope="col">Name</th>
              <th scope="col">Id</th>
              <th scope="col">Link</th>
            </tr>
          </thead>
          <tbody>{calumns}</tbody>
        </table>
      </div>
    </div>
  );
}
